Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

General: Cache course icons and profile pictures to improve performance #9459

Merged
merged 4 commits into from
Oct 12, 2024

Conversation

krusche
Copy link
Member

@krusche krusche commented Oct 12, 2024

Checklist

General

  • I tested all changes and their related features with all corresponding user types on a test server.
  • This is a small issue that I tested locally and was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Motivation and Context

Improve performance by caching images that do not change

Steps for Testing

Prerequisites:

  • 1 Student
  1. Log in to Artemis
  2. Make sure course icons are only loaded once from the server (in the dev tools)
  3. Navigate into communication and make sure profile pictures are only loaded once from the server (in the dev tools)

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Summary by CodeRabbit

  • New Features

    • Enhanced static resource serving capabilities for images, including course icons and user profile pictures.
    • Improved post management in the conversation messages component, allowing real-time updates.
  • Bug Fixes

    • Implemented caching for file responses, optimizing performance with a 30-day cache control directive.
    • Updated content type handling for quiz exercise files based on file extensions.
  • Refactor

    • Improved type clarity in the conversation service for better maintainability.
    • Expanded test coverage for course functionalities, enhancing reliability and user experience.

@krusche krusche requested a review from a team as a code owner October 12, 2024 19:34
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module labels Oct 12, 2024
@krusche krusche added this to the 7.6.0 milestone Oct 12, 2024
Copy link

coderabbitai bot commented Oct 12, 2024

Walkthrough

The pull request introduces several updates across multiple classes. The PublicResourcesConfiguration class now includes a fileUploadPath field for serving static resources. The FileResource class implements caching headers for file responses. In the Angular component ConversationMessagesComponent, a method for subscribing to updates from the metisService is added, and the order of posts is reversed before assignment. Lastly, the MetisConversationService class enhances type clarity for a variable in the setActiveConversation method. The CourseTestService class has extensive new tests for various course functionalities, while the QuizExerciseIntegrationTest class updates expected content types for quiz-related files.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/core/config/PublicResourcesConfiguration.java Added fileUploadPath field and modified addResourceHandlers method for serving static resources.
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java Added caching headers to responseEntityForFilePath method and updated content type determination.
src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts Added subscribeToMetis() method and updated ngOnInit() to subscribe to posts; modified setPosts to reverse post order.
src/main/webapp/app/shared/metis/metis-conversation.service.ts Updated type declaration for cachedConversation in setActiveConversation method.
src/test/java/de/tum/cit/aet/artemis/core/util/CourseTestService.java Added multiple new test methods for comprehensive course functionality testing.
src/test/java/de/tum/cit/aet/artemis/quiz/QuizExerciseIntegrationTest.java Updated checkCreatedFile method to dynamically determine expected content type for quiz exercise files.

Possibly related PRs

Suggested labels

tests, ready to merge, communication, small

Suggested reviewers

  • JohannesStoehr
  • MaximilianAnzinger
  • SimonEntholzer
  • pzdr7

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range comments (5)
src/main/java/de/tum/cit/aet/artemis/core/config/PublicResourcesConfiguration.java (1)

Line range hint 36-62: Summary: Caching implementation for static resources looks good

The changes to PublicResourcesConfiguration successfully implement caching for course icons, profile pictures, and drag-and-drop quiz pictures. This aligns with the PR objective of improving performance by reducing the number of times these images are loaded from the server.

Key points:

  1. The fileUploadPath is correctly injected using @Value.
  2. Resource handlers are added for each type of static resource.
  3. Caching is applied consistently using defaultCacheControl.

Suggestions for improvement:

  1. Address the TODO comment by extracting path constants to avoid duplication.
  2. Consider minor formatting adjustments for consistency.

Overall, these changes should contribute to improved performance as intended. Remember to update the relevant tests and documentation to reflect these changes.

src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (2)

Line range hint 139-149: LGTM! Consider calling subscribeToMetis() in ngOnInit().

The new subscribeToMetis() method is well-implemented and follows Angular best practices. It correctly subscribes to the necessary observables and updates the component's state.

To ensure this subscription is set up when the component initializes, consider adding a call to subscribeToMetis() in the ngOnInit() method.

You can add the following line to the ngOnInit() method:

this.subscribeToMetis();

Line range hint 172-172: LGTM! Consider using arrow function syntax.

The modification to reverse the order of posts before assignment is a good change that aligns with the PR objectives. This will likely improve the performance of the component when rendering posts.

To maintain consistency with the coding guidelines, consider using arrow function syntax for this method.

You can refactor the method as follows:

setPosts = (posts: Post[]): void => {
    if (this.content) {
        this.previousScrollDistanceFromTop = this.content.nativeElement.scrollHeight - this.content.nativeElement.scrollTop;
    }
    this.posts = posts.slice().reverse();
};
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (2)

Line range hint 1-665: Consider reviewing and aligning caching across all relevant endpoints.

While the changes in the responseEntityForFilePath method are excellent, it might be beneficial to ensure consistency in caching across all relevant endpoints in this file.

Review other methods that serve files, such as getCourseIcon, getProfilePicture, and others, to ensure they also implement appropriate caching strategies. This would provide a consistent performance improvement across the application.

For example, you might want to update the getCourseIcon method:

@GetMapping("files/course/icons/{courseId}/*")
@EnforceAtLeastStudent
public ResponseEntity<byte[]> getCourseIcon(@PathVariable Long courseId) {
    log.debug("REST request to get icon for course : {}", courseId);
    Course course = courseRepository.findByIdElseThrow(courseId);
-   return responseEntityForFilePath(getActualPathFromPublicPathString(course.getCourseIcon()));
+   return responseEntityForFilePath(getActualPathFromPublicPathString(course.getCourseIcon())).cacheControl(CacheControl.maxAge(FILE_CACHE_DAYS, TimeUnit.DAYS));
}

Apply similar changes to other relevant methods to ensure consistent caching behavior across the application.


Caching not properly implemented for course icons and profile pictures.

The current implementation of getCourseIcon and getProfilePicture does not enable caching by setting the cache parameter to true in the responseEntityForFilePath method. This means caching headers are not applied, contrary to the PR objectives.

Recommendation:

  • Update the getCourseIcon and getProfilePicture methods to call responseEntityForFilePath with the cache parameter set to true to ensure proper caching.
🔗 Analysis chain

Line range hint 1-665: Verify caching implementation for course icons and profile pictures.

The PR objectives mention caching course icons and profile pictures. While the changes in the responseEntityForFilePath method provide a good foundation for caching, we should verify that this implementation effectively caches these specific resources.

To ensure that the caching is correctly applied to course icons and profile pictures, we can run the following script:

This script will help us verify that the caching implementation is correctly applied to the course icons and profile pictures, as specified in the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify caching implementation for course icons and profile pictures

# Test: Check if caching is applied to course icon endpoints
echo "Checking course icon endpoints:"
rg --type java -C 3 "files/course/icons.*ResponseEntity"

# Test: Check if caching is applied to profile picture endpoints
echo "Checking profile picture endpoints:"
rg --type java -C 3 "files/user/profile-pictures.*ResponseEntity"

# Test: Verify that responseEntityForFilePath is used in these methods
echo "Verifying usage of responseEntityForFilePath:"
rg --type java -C 3 "responseEntityForFilePath.*course.getCourseIcon"
rg --type java -C 3 "responseEntityForFilePath.*user.getImageUrl"

Length of output: 2178

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between d801ef8 and ae3d541.

📒 Files selected for processing (4)
  • src/main/java/de/tum/cit/aet/artemis/core/config/PublicResourcesConfiguration.java (3 hunks)
  • src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (2 hunks)
  • src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (1 hunks)
  • src/main/webapp/app/shared/metis/metis-conversation.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
src/main/java/de/tum/cit/aet/artemis/core/config/PublicResourcesConfiguration.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/shared/metis/metis-conversation.service.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🔇 Additional comments (5)
src/main/java/de/tum/cit/aet/artemis/core/config/PublicResourcesConfiguration.java (2)

36-37: LGTM: New field added correctly

The fileUploadPath field is correctly added and follows the coding guidelines. It uses the @Value annotation for property injection, which is appropriate for configuration values.


59-60: LGTM: Resource handler for profile pictures added correctly

The resource handler for user profile pictures is well-implemented. It correctly uses the fileUploadPath and applies caching. The code is also formatted for good readability.

src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (1)

Line range hint 1-280: Overall, the changes look good and align with the PR objectives.

The modifications to the ConversationMessagesComponent improve data management and should enhance performance. The new subscribeToMetis() method and the changes to setPosts() are well-implemented and follow Angular best practices.

A few minor suggestions have been made to further improve the code:

  1. Call subscribeToMetis() in the ngOnInit() method to ensure the subscriptions are set up when the component initializes.
  2. Consider using arrow function syntax for the setPosts() method to maintain consistency with the coding guidelines.

These changes contribute positively to the overall goal of caching course icons and profile pictures to improve performance.

src/main/webapp/app/shared/metis/metis-conversation.service.ts (1)

119-119: Improved type safety with explicit typing

The change to explicitly type cachedConversation as ConversationDTO | undefined enhances code clarity and type safety. This aligns well with TypeScript best practices and Angular style guidelines.

src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (1)

Line range hint 1-665: Summary: Excellent caching implementation with room for further optimization.

The changes made to the responseEntityForFilePath method significantly improve the application's performance by implementing caching for file responses. This aligns well with the PR objectives of caching course icons and profile pictures.

Key points:

  1. Caching is now implemented for file responses with a 30-day duration.
  2. The content type is dynamically set based on the filename, improving flexibility.

Suggestions for further improvement:

  1. Extract the cache duration into a constant for better maintainability.
  2. Review and align caching strategies across all relevant endpoints in the file.
  3. Verify the specific implementation for course icons and profile pictures.

Overall, these changes provide a solid foundation for improving the application's performance. Implementing the suggested improvements will further enhance the caching strategy and ensure consistency across the application.

PaRangger
PaRangger previously approved these changes Oct 12, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 12, 2024
@github-actions github-actions bot added tests quiz Pull requests that affect the corresponding module labels Oct 12, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range comments (6)
src/test/java/de/tum/cit/aet/artemis/core/util/CourseTestService.java (6)

Line range hint 487-488: Missing @Test Annotation on Test Methods

The test methods are missing the @Test annotation from JUnit 5, which is necessary for the test runner to recognize and execute them.

Apply this diff to add the @Test annotation to each test method:

+import org.junit.jupiter.api.Test;

 // Test
+@Test
 public void testCreateCourseWithPermission() throws Exception {
     // test implementation
 }

 // Test
+@Test
 public void testCreateCourseWithSameShortName() throws Exception {
     // test implementation
 }

 // Test
+@Test
 private void testCreateCourseWithNegativeValue(Course course) throws Exception {
     // test implementation
 }

 // Test
+@Test
 public void testCreateCourseWithNegativeMaxComplainNumber() throws Exception {
     // test implementation
 }
 
 // Continue adding @Test annotations to the remaining test methods...

Also applies to: 495-496, 503-504, 511-512, 519-520, 527-528, 537-538, 545-546, 553-554


Line range hint 675-683: Avoid Using Magic Numbers in Test Setup

In the setup method, NUMBER_OF_STUDENTS, NUMBER_OF_TUTORS, NUMBER_OF_EDITORS, and NUMBER_OF_INSTRUCTORS are hardcoded values. It's better to use constants or configuration parameters to improve readability and maintainability.

Consider defining these numbers as configurable constants or parameters:

 public class CourseTestService {

     private static final int NUMBER_OF_STUDENTS = 8;
     private static final int NUMBER_OF_TUTORS = 5;
     private static final int NUMBER_OF_EDITORS = 1;
     private static final int NUMBER_OF_INSTRUCTORS = 1;

     public void setup(String userPrefix, MockDelegate mockDelegate) {
-        userUtilService.addUsers(userPrefix, 8, 5, 1, 1);
+        userUtilService.addUsers(userPrefix, NUMBER_OF_STUDENTS, NUMBER_OF_TUTORS, NUMBER_OF_EDITORS, NUMBER_OF_INSTRUCTORS);
         // rest of the setup method...
     }

Line range hint 1824-1834: Handle Potential NullPointerException

In the method testGetCourseForDashboard, the variable courses.getFirst() is used without checking if the list courses is not empty. This could lead to a NullPointerException if courses is empty.

Consider adding a check to ensure that courses is not empty before calling getFirst():

 public void testGetCourseForDashboard(boolean userRefresh) throws Exception {
     List<Course> courses = courseUtilService.createCoursesWithExercisesAndLecturesAndLectureUnitsAndCompetencies(userPrefix, true, false, NUMBER_OF_TUTORS);
+    if (courses.isEmpty()) {
+        throw new IllegalStateException("Course list is empty.");
+    }
     CourseForDashboardDTO receivedCourseForDashboard = request.get("/api/courses/" + courses.getFirst().getId() + "/for-dashboard?refresh=" + userRefresh, HttpStatus.OK,
             CourseForDashboardDTO.class);
     Course receivedCourse = receivedCourseForDashboard.course();
     // rest of the method...
 }

Line range hint 2446-2460: Possible Redundant Null Check

In the method testArchiveCourseWithTestModelingAndFileUploadExercises, after the archiving process, the code retrieves the updated course and checks assertThat(updatedCourse.getCourseArchivePath()).isNotEmpty();. Since getCourseArchivePath() returns a String, which cannot be null when isNotEmpty() is called, the null check might be redundant.

Ensure that the null check is necessary; otherwise, consider removing it to clean up the code.


Line range hint 799-806: Unused Import Statements

There are several unused import statements at the top of the file. Unused imports can clutter the code and may lead to confusion.

Consider removing unused imports to clean up the code.

For example:

-import org.mockito.MockedStatic;

Line range hint 2540-2546: Consistent Use of Assertions

In testDownloadCourseArchiveAsInstructor_not_found, the assertion checks for assertThat(downloadedArchive).isNull();. In other test methods, similar checks use assertThat(response).as("message").isNull();. For consistency, consider adding a description to the assertion.

-assertThat(downloadedArchive).isNull();
+assertThat(downloadedArchive).as("No archive should be downloaded as it does not exist").isNull();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between ae3d541 and caddaec.

📒 Files selected for processing (2)
  • src/test/java/de/tum/cit/aet/artemis/core/util/CourseTestService.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/quiz/QuizExerciseIntegrationTest.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/test/java/de/tum/cit/aet/artemis/core/util/CourseTestService.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

src/test/java/de/tum/cit/aet/artemis/quiz/QuizExerciseIntegrationTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

🔇 Additional comments (2)
src/test/java/de/tum/cit/aet/artemis/core/util/CourseTestService.java (2)

Line range hint 1592-1604: Exception Handling in Test Methods

The method testEnrollInCourse_notMeetsDate does not include assertions to verify that the expected exceptions are thrown when enrollment dates are not met.

Add assertions to check that the correct exceptions or error responses are received.

// Add assertions to verify that enrollment fails due to date constraints
request.post("/api/courses/" + notYetStartedCourse.getId() + "/enroll", User.class, HttpStatus.FORBIDDEN);
request.post("/api/courses/" + finishedCourse.getId() + "/enroll", User.class, HttpStatus.FORBIDDEN);

Line range hint 3058-3060: Potential Misuse of Mocking Libraries

In testUpdateCourse_instructorNotInCourse, the method uses the request object to perform a request and expects a FORBIDDEN response. Ensure that the mocking is appropriately set up to simulate the instructor not being in the course.

Review the mocking setup to confirm that it correctly reflects the user permissions.

@krusche krusche merged commit 330a677 into develop Oct 12, 2024
23 of 28 checks passed
@krusche krusche deleted the feature/cache-images branch October 12, 2024 20:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module quiz Pull requests that affect the corresponding module server Pull requests that update Java code. (Added Automatically!) tests
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

2 participants